package com.sy.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.sy.dto.*;
import com.sy.entity.*;
import com.sy.service.AnnouncementService;
import com.sy.utils.RedisOperations;
import com.sy.vo.*;

import com.sy.vo.ChangePwdVo;
import com.sy.vo.StuInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import static com.sy.constant.StudentConstant.ANNOUNCEMENT_COUNT;
import static com.sy.constant.StudentConstant.CORRECTION_STATUS;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.sy.constant.BusinessConstant.REDIS_USER_KEY_PREFIX;
import static com.sy.constant.BusinessConstant.USER_SESSION_MAX_AGE;
import static com.sy.constant.StudentConstant.*;

@RestController
public class StudentController extends BaseController {
    @Autowired
    private AnnouncementService announcementService;

    /**
     * 公告栏部分，从数据库取出最新的十条公告
     */
    @RequestMapping(value = "announcements", method = RequestMethod.POST)
    public List<Announcement> getTenAnnouncements() {
        List<Announcement> announcement = announcementService.getAnnouncement(ANNOUNCEMENT_COUNT);
        return announcement;
    }

    //获取学生的信息
    @RequestMapping(value = "student", method = RequestMethod.GET)
    public StuInfo getStuInfo() {
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
        return studentService.getStuInfo(String.valueOf(id));
    }


    //更新学生的信息
    @RequestMapping(value = "student", method = RequestMethod.PUT, params = {"type=updateStuInfo"})
    public StuInfoVo updateStuInfo(String name, String gender, String phone, String classId) {
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
        StuInfoVo stuInfoVo = new StuInfoVo();
        stuInfoVo.setId(String.valueOf(id));
        stuInfoVo.setName(name);
        stuInfoVo.setPhone(phone);
        stuInfoVo.setGender(gender);
        stuInfoVo.setClassId(classId);
        studentService.updateStuInfo(stuInfoVo);
        return stuInfoVo;
    }

    //更改学生的密码
    @RequestMapping(value = "student", method = RequestMethod.PUT, params = {"type=changeStuPwd"})
    public ChangePwdVo changeStuPwd(String oldPwd, String newPwd, String verCode) {
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
//        ChangePwdVo changePwdVo = new ChangePwdVo();
//        changePwdVo.setId(String.valueOf(id));
//        changePwdVo.setOldPwd(oldPwd);
//        changePwdVo.setNewPwd(newPwd);
//        changePwdVo.setVerCode(verCode);
//        loginService.changePwd(changePwdVo);
//        return changePwdVo;
        return null;
    }

    /**
     * 从后端获取学生没做的作业列表并且开启分页
     */
    @RequestMapping(value = "students", method = RequestMethod.GET, params = {"type=notDoHomeWork", "page", "limit"})
    public Table getStudentNotDoHomeWork(Integer page, Integer limit, Integer classId) {
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        System.out.println(session.getId());
        Integer id = session.getId();
        classId = studentService.getStudentsMessage(String.valueOf(id)).getClassId();
        Page<HomeWorkMessage> allNotDoHomeWork = studentService.getAllNotDoHomeWork(String.valueOf(id), "", page, limit, classId);
//
        return getTable(allNotDoHomeWork);
    }

    /**
     * 根据搜索查询
     *
     * @param page
     * @param limit
     * @param title
     */
    @RequestMapping(value = "/students", method = RequestMethod.GET, params = {"type=notDoHomeWork", "page", "limit", "title"})
    public Table getNotDoHomeworkListByKeywords(Integer page, Integer limit, String title, Integer classId) throws UnsupportedEncodingException {
        String decode = URLDecoder.decode(title, "UTF-8");
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        System.out.println(session.getId());
        Integer id = session.getId();
        classId = studentService.getStudentsMessage(String.valueOf(id)).getClassId();
        Page<HomeWorkMessage> allNotDoHomeWork = studentService.getAllNotDoHomeWork(String.valueOf(id), decode, page, limit, classId);
        return getTable(allNotDoHomeWork);
    }

    /**
     * 根据搜索查询
     *
     * @param page
     * @param limit
     * @param title
     */
    @RequestMapping(value = "/students", method = RequestMethod.GET, params = {"type=haveDoHomeWork", "page", "limit", "title"})
    public Table getHaveDoHomeworkListByKeywords(Integer page, Integer limit, String title, Integer classId) throws UnsupportedEncodingException {
        String decode = URLDecoder.decode(title, "UTF-8");
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        System.out.println(session.getId());
        Integer id = session.getId();
        classId = studentService.getStudentsMessage(String.valueOf(id)).getClassId();
        Page<HomeWorkMessage> allNotDoHomeWork = studentService.getAllHaveDoHomeWork(String.valueOf(id), decode, page, limit, classId);
        return getTable(allNotDoHomeWork);
    }

    /**
     * 拿到学生的成绩信息并开启分页
     */

    @RequestMapping(value = "/students", method = RequestMethod.GET, params = {"type=score", "page", "limit"})
    public Table getStudentsScore(Integer page, Integer limit) {
//         req.getSession().getAttribute("session").getClass()
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
        System.out.println("-----------------------------");
        Page<StudentShowScore> studentGradeById = studentService.getStudentGradeById(String.valueOf(id), "", page, limit, CORRECTION_STATUS);
        return getTable(studentGradeById);
    }

    /**
     * 根据搜索查询
     *
     * @param page
     * @param limit
     * @param title
     */
    @RequestMapping(value = "/students", method = RequestMethod.GET, params = {"type=score", "page", "limit", "title"})
    public Table getStudentsScoreByKeywords(Integer page, Integer limit, String title) throws UnsupportedEncodingException {
        String decode = URLDecoder.decode(title, "UTF-8");
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
        System.out.println("-----------------------------");
        Page<StudentShowScore> studentGradeById = studentService.getStudentGradeById(String.valueOf(id), decode, page, limit, CORRECTION_STATUS);
        return getTable(studentGradeById);
    }

    /**
     * 学生根据自己所属老师去查询老师上传的文件,并开启分页
     */
    @RequestMapping(value = "/students", method = RequestMethod.GET, params = {"type=getStudyFile", "page", "limit"})
    public Table getTeacherUploadFile(Integer page, Integer limit) {
//        先得到学生的id
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
//        根据学生的id得到学生班级的id
        Student studentsMessage = studentService.getStudentsMessage(String.valueOf(id));
        Integer classId = studentsMessage.getClassId();
//        根据学生班级的id得到对应老师的id
        ClassMsg classMsg = studentService.selectTeacherByClassId(classId);
        Integer teacherId = classMsg.getTeacherId();
//        再根据老师的id去查询到老师上传的文件
        Page<StudentDownloadCourseware> teacherUploadFile = studentService.getTeacherUploadFile(teacherId, "", page, limit);
        return getTable(teacherUploadFile);

    }

    /**
     * 根据关键词搜索查询
     *
     * @param page
     * @param limit
     * @param title
     */
    @RequestMapping(value = "/students", method = RequestMethod.GET, params = {"type=getStudyFile", "page", "limit", "title"})
    public Table getTeacherUploadFileByKeywords(Integer page, Integer limit, String title) throws UnsupportedEncodingException {
        String decode = URLDecoder.decode(title, "UTF-8");
//        先得到学生的id
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
//        根据学生的id得到学生班级的id
        Student studentsMessage = studentService.getStudentsMessage(String.valueOf(id));
        Integer classId = studentsMessage.getClassId();
        System.out.println("classId11111111111111"+classId);
//        根据学生班级的id得到对应老师的id
        ClassMsg classMsg = studentService.selectTeacherByClassId(classId);
        Integer teacherId = classMsg.getTeacherId();
//        再根据老师的id去查询到老师上传的文件
        Page<StudentDownloadCourseware> teacherUploadFile = studentService.getTeacherUploadFile(teacherId, decode, page, limit);
        return getTable(teacherUploadFile);
    }

    /**
     * 学生做完作业后提交作业
     */
    @RequestMapping(value = "/students", method = RequestMethod.POST, params = {"type=submitHomework"})
    public void studentsSubmitHomework(@RequestBody StudentSubmitAnswer studentSubmitAnswer) {
//      1、  先将拿到的数据往Redis里存储
        System.out.println("------------------------");
        System.out.println(studentSubmitAnswer);
        System.out.println("------------------------");
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
        Integer titleId = studentSubmitAnswer.getHomeworkId();
        String s = String.valueOf(id);
        String s1 = String.valueOf(titleId);
////        用学生的id和题目的id合起来(学生id和题目的id都是唯一)作为key
//        String key = REDIS_USER_KEY_PREFIX + s + REDIS_KEY + s1;
////       将对应的studentSubmitAnswer作为value存入redis中
//        JSONObject json = (JSONObject) JSONObject.toJSON(studentSubmitAnswer);//将java对象转换为json对象
//        String str = json.toString();//将json对象转换为字符串
//        redisOperations.set(key, str);
////        设置Redis时间为7天
//        redisOperations.expire(key, USER_SESSION_MAX_AGE);
//        2、再将拿到的数据往数据库里存储
        studentService.insertHomeWorkAllAnswer(studentSubmitAnswer, id);
    }

    /**
     * 从后端获取学生已经做完的的作业列表并且开启分页
     */
    @RequestMapping(value = "students", method = RequestMethod.GET, params = {"type=haveDoHomeWork", "page", "limit"})
    public Table getStudentHaveDoHomeWork(Integer page, Integer limit, Integer classId) {
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        System.out.println(session.getId());
        Integer id = session.getId();
        classId = studentService.getStudentsMessage(String.valueOf(id)).getClassId();
        Page<HomeWorkMessage> allNotDoHomeWork = studentService.getAllHaveDoHomeWork(String.valueOf(id), "", page, limit, classId);
        return getTable(allNotDoHomeWork);
    }

    /**
     * 从后端获取学生没做的作业详细内容包括选择简答题
     */
    @RequestMapping(value = "students/{id}", method = RequestMethod.GET, params = {"type=notDoHomeWorkDetail"})
    public ReturnHomeWork getStudentNotDoHomeWorkDetail(@PathVariable("id") String id) {
        List<ChoiceQuestion> allQuestionsByHomeWorkId = studentService.getAllQuestionsByHomeWorkId(id);
        ShortQuestion studentNotDoHomeWorkShortQuestion = studentService.getStudentNotDoHomeWorkShortQuestion(id);
        ReturnHomeWork returnHomeWork = new ReturnHomeWork();
        returnHomeWork.setChoiceQuestions(allQuestionsByHomeWorkId);
        returnHomeWork.setShortQuestion(studentNotDoHomeWorkShortQuestion);
        return returnHomeWork;
    }

    @RequestMapping(value = "students", method = RequestMethod.GET, params = {"type=noSubmit", "homeworkId", "page", "limit"})
    public Table getStudentsNoSubmit (Integer homeworkId, Integer page, Integer limit){
        Page<StudentMagTable> studentsNoSubmit = studentService.getStudentsNoSubmit(homeworkId, page, limit);
        return getTable(studentsNoSubmit);
    }

    /**
     * 从后端获取学生已经做的作业详细内容包括选择简答题,包括所写的内容，ReturnHomeWorkAnswer作为整个返回的类型
     */
    @RequestMapping(value = "students/{id}", method = RequestMethod.GET, params = {"type=haveDoHomeWorkDetail"})
    public ReturnHomeWorkAnswer getStudenthaveDoHomeWorkDetail(@PathVariable("id") String id) {
        List<ChoiceQuestion> allQuestionsByHomeWorkId = studentService.getAllQuestionsByHomeWorkId(id);
        ShortQuestion studentNotDoHomeWorkShortQuestion = studentService.getStudentNotDoHomeWorkShortQuestion(id);
        ReturnHomeWork returnHomeWork = new ReturnHomeWork();
        returnHomeWork.setChoiceQuestions(allQuestionsByHomeWorkId);
        returnHomeWork.setShortQuestion(studentNotDoHomeWorkShortQuestion);
//        先拿到所有的题目和选项的id
        ReturnHomeWorkAnswer returnHomeWorkAnswer = new ReturnHomeWorkAnswer();
        returnHomeWorkAnswer.setReturnHomeWork(returnHomeWork);
////        1、先从redis里面去取
        UserSession session = (UserSession) req.getSession().getAttribute("session");
//        拿到学生的id
        Integer id1 = session.getId();
//        String s = String.valueOf(id1);
////        拿到学生对应的redis里的key
//        String key = REDIS_USER_KEY_PREFIX + s + REDIS_KEY + id;
//
////        先做判断redis里面有没有这个key
//        if (redisOperations.exists(key)) {
////            再去redis去查找之前填写过的答案
//            String s1 = redisOperations.get(key);
////        再转换成对应的对象
//            StudentSubmitAnswer studentSubmitAnswer = JSONObject.parseObject(s1, StudentSubmitAnswer.class);
//            System.out.println(studentSubmitAnswer);
//            returnHomeWorkAnswer.setStudentSubmitAnswer(studentSubmitAnswer);
//        } else {
//        String key=REDIS_USER_KEY_PREFIX+s+REDIS_KEY+id;
////        先做判断redis里面有没有这个key
//        if(redisOperations.exists(key)){
////            再去redis去查找之前填写过的答案
//            String s1 = redisOperations.get(key);
////        再转换成对应的对象
//            StudentSubmitAnswer studentSubmitAnswer = JSONObject.parseObject(s1, StudentSubmitAnswer.class);
//            System.out.println(studentSubmitAnswer);
//            returnHomeWorkAnswer.setStudentSubmitAnswer(studentSubmitAnswer);
//        }else {
//            没有再去数据库里查找
            int homeworkId = Integer.parseInt(id);
            ShortAnswer shortAnswer = studentService.selectSubmitShortAnswer(homeworkId,id1);
            List<Answers> answers = studentService.selectSubmitChoiceAnswer(homeworkId,id1);
            StudentSubmitAnswer studentSubmitAnswer = new StudentSubmitAnswer();
            studentSubmitAnswer.setHomeworkId(homeworkId);
            studentSubmitAnswer.setAnswers(answers);
            studentSubmitAnswer.setShortAnswer(shortAnswer);
            returnHomeWorkAnswer.setStudentSubmitAnswer(studentSubmitAnswer);
//        }
        return returnHomeWorkAnswer;
//             List<Answers> answers = studentService.selectSubmitChoiceAnswer(homeworkId);
//             StudentSubmitAnswer studentSubmitAnswer = new StudentSubmitAnswer();
//             studentSubmitAnswer.setHomeworkId(homeworkId);
//             studentSubmitAnswer.setAnswers(answers);
//             studentSubmitAnswer.setShortAnswer(shortAnswer);
//             returnHomeWorkAnswer.setStudentSubmitAnswer(studentSubmitAnswer);
////        }
//        return  returnHomeWorkAnswer;
    }

    /**
     * 学生修改完作业后提交作业
     */
    @RequestMapping(value = "/students", method = RequestMethod.POST, params = {"type=modifyhomeWork"})
    public void studentsModifyHomeWork(@RequestBody StudentSubmitAnswer studentSubmitAnswer) {
//      1、  先将拿到的数据往Redis里存储
        System.out.println("------------------------");
        System.out.println(studentSubmitAnswer);
        System.out.println("------------------------");
        UserSession session = (UserSession) req.getSession().getAttribute("session");
        Integer id = session.getId();
        Integer titleId = studentSubmitAnswer.getHomeworkId();
        String s = String.valueOf(id);
        String s1 = String.valueOf(titleId);
//        用学生的id和题目的id合起来(学生id和题目的id都是唯一)作为key
//        String key = REDIS_USER_KEY_PREFIX + s + REDIS_KEY + s1;
////        将之前在redis中的数据删除重新写入新的答案
//        redisOperations.del(key);
////       再将对应的studentSubmitAnswer作为value存入redis中
//        JSONObject json = (JSONObject) JSONObject.toJSON(studentSubmitAnswer);//将java对象转换为json对象
//        String str = json.toString();//将json对象转换为字符串
//        redisOperations.set(key, str);
////        设置Redis时间为7天
//        redisOperations.expire(key, USER_SESSION_MAX_AGE);
//        redisOperations.del(key);
////       再将对应的studentSubmitAnswer作为value存入redis中
//        JSONObject json = ( JSONObject)JSONObject.toJSON(studentSubmitAnswer);//将java对象转换为json对象
//        String str = json.toString();//将json对象转换为字符串
//        redisOperations.set(key,str);
////        设置Redis时间为7天
//        redisOperations.expire(key, USER_SESSION_MAX_AGE);
////        2、再将在数据库里的数据进行修改
        studentService.updateAllAnswer(studentSubmitAnswer, id);
    }


    /**
     *查找学生的个人信息
     */
    @RequestMapping(value="/students",method = RequestMethod.GET,params = {"type=studentOwnMessage"})
    public StudentAllMessages  selectStudentOwnMessage(){
//        先拿到学生的个人信息
       UserSession session = (UserSession)req.getSession().getAttribute("session");
        Integer id = session.getId();
        Student student = studentService.selectStudentsOwnMessage(id);
//        取出学生的班级id
       Integer classId = student.getClassId();
//       在通过学生的班级id取出学生的班级信息
        ClassMsg classMsg = studentService.selectClassMessageByClassId(classId);
         StudentAllMessages studentAllMessages = new StudentAllMessages();
         studentAllMessages.setClassMsg(classMsg);
         studentAllMessages.setStudent(student);
         return  studentAllMessages;
    }


    /**
     *学生修改信息后提交到后端进行修改
     */

    @RequestMapping(value = "/students",method = RequestMethod.PUT,params = {"type=updateStudentMessage"})
    public  void updateStudentMessage(@RequestBody NewStudentsMessage newStudentsMessage){
       UserSession session = (UserSession)req.getSession().getAttribute("session");
//       取出学生的id
         Integer id = session.getId();
//         取出学生新修改的名字
         String name = newStudentsMessage.getName();
//        取出学生新填写的手机号
         Long phone = newStudentsMessage.getPhone();
//         取出学生填写的性别
        String sex = newStudentsMessage.getSex();
        studentService.updateStudentNewMessage(name,sex,String.valueOf(phone),id);
    }

    /**
     * 学生修改密码
     */

    @RequestMapping(value = "/students",method = RequestMethod.PUT,params = {"type=modifyPassword"})
    public void  StudentModifyPassword(@RequestBody StudentModifyPasswordVo studentModifyPasswordVo){
//        System.out.println(studentModifyPasswordVo);
       UserSession session =(UserSession) req.getSession().getAttribute("session");
//       拿到学生的id
         Integer id = session.getId();
//        拿到确认的密码
         String confirmNewPassword = studentModifyPasswordVo.getConfirmNewPassword();
//         拿到新的密码
          String newPassword = studentModifyPasswordVo.getNewPassword();
//          拿到旧密码
         String oldPassword = studentModifyPasswordVo.getOldPassword();
         studentService.updateStudentPassword(oldPassword,id,confirmNewPassword,newPassword);
    }


    /**
     *学生登陆后从后端拿到学生的名字
     */
    @RequestMapping(value = "/students",method = RequestMethod.GET,params = {"type=getStudentName"})
    public Student  getStudentName(){
       UserSession session =(UserSession) req.getSession().getAttribute("session");
       Student studentsMessage = studentService.getStudentsMessage(String.valueOf(session.getId()));
       return studentsMessage;

//
    }


    /**
     * 渲染已经修改过的学生的问卷
     */
    @RequestMapping(value = "/students/{titles}",method = RequestMethod.GET,params = {"type=correctingDoHomeWorkDetail"})
    public ReturnCorrectHomeWorkAnswer   correctingDoHomeWorkDetail(@PathVariable("titles") String titles)throws UnsupportedEncodingException{
        String decode = URLDecoder.decode(titles, "UTF-8");

        System.out.println(decode);
       ReturnCorrectHomeWorkAnswer returnCorrectHomeWorkAnswer = new ReturnCorrectHomeWorkAnswer();
//        根据作业的标题查到作业对应的id
         Homework homework = studentService.selectHomeWorkIdByTitle(decode);
        Integer id = homework.getId();
//        根据作业的id去查询对应的选择题的id
       List<ChoiceAnswer> choiceQues = studentService.selectAllChoiceIdByHomeworkId(id);
//       再根据选择题对应的id去查询对应的答案
//        先创建一个空的集合
        System.out.println(choiceQues);
        ArrayList<Choice> choices = new ArrayList<>();
        for (int i = 0; i < choiceQues.size(); i++) {
            Integer id1 = choiceQues.get(i).getChoiceAnswer();

             Choice choice = studentService.selectTrueChoiceAnswerByChoiceId(id1);
//             将查到的对应的选择题的答案放入集合中
              choices.add(choice);
        }


        List<ChoiceQuestion> allQuestionsByHomeWorkId = studentService.getAllQuestionsByHomeWorkId(String.valueOf(id));
        ShortQuestion studentNotDoHomeWorkShortQuestion = studentService.getStudentNotDoHomeWorkShortQuestion(String.valueOf(id));
        ReturnHomeWork returnHomeWork = new ReturnHomeWork();
        returnHomeWork.setChoiceQuestions(allQuestionsByHomeWorkId);
        returnHomeWork.setShortQuestion(studentNotDoHomeWorkShortQuestion);
//        先拿到所有的题目和选项的id
        ReturnHomeWorkAnswer returnHomeWorkAnswer = new ReturnHomeWorkAnswer();
        returnHomeWorkAnswer.setReturnHomeWork(returnHomeWork);
//        int homeworkId = Integer.parseInt(id);
        ShortAnswer shortAnswer = studentService.selectSubmitShortAnswer(id,getSessionUserId());
        List<Answers> answers = studentService.selectSubmitChoiceAnswer(id,getSessionUserId());
        StudentSubmitAnswer studentSubmitAnswer = new StudentSubmitAnswer();
        studentSubmitAnswer.setHomeworkId(id);
        studentSubmitAnswer.setAnswers(answers);
        studentSubmitAnswer.setShortAnswer(shortAnswer);
        returnHomeWorkAnswer.setStudentSubmitAnswer(studentSubmitAnswer);


        returnCorrectHomeWorkAnswer.setChoices(choices);
        returnCorrectHomeWorkAnswer.setReturnHomeWork(returnHomeWork);
        returnCorrectHomeWorkAnswer.setStudentSubmitAnswer(studentSubmitAnswer);
        return returnCorrectHomeWorkAnswer;
//
    }

}
